package com.exm.collectcodenew.juc.aqs;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CycleBarrierExample {
//    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{System.out.println("Runnable is running!");});
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService= Executors.newCachedThreadPool();
        for (int i = 0; i < 6; i++) {
            final int threadNum =i;
            Thread.sleep(1000);
            executorService.execute(()->{
                try {
                    test(threadNum);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        executorService.shutdown();
    }
    private static void test(int threadNum) throws Exception {
        Thread.sleep(1000);
        System.out.println(threadNum+ " is ready");
        cyclicBarrier.await();
        System.out.println(threadNum+ " is continue");
    }
}
